/* =========================================================================

DESCRIPTION
   cae_app

Copyright (c) 2015 by  USTC iFLYTEK, Co,LTD.  All Rights Reserved.
============================================================================ */

/* =========================================================================

                             REVISION

when            who              why
--------        ---------        -------------------------------------------
2015/12/22     qfgao               Created.
============================================================================ */
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <assert.h>
#include <string.h>

#define CHIP_ADDR  (0x47)

int open_i2c_device(const char * devname)
{
	int h;
	// open device
	h = open(devname, O_RDWR);
	if(h < 0) {
		printf("open_i2c(): open %s failed\n", devname);
		return -1;
	}else{
		printf("open success!!!\n");
	}
	return h;
}

void close_i2c_device(int handle)
{
	if (handle) {
		close(handle);
	}
}

bool  write_i2c_device(int handle,int addr,const unsigned char *pbuf)
{
	int ret;
	int count = 1;
	unsigned char buff[8] = {addr,pbuf[0],pbuf[1],pbuf[2],pbuf[3],0};
	struct i2c_msg msgs[1] = { {CHIP_ADDR, 0, 5, buff} };
	struct i2c_rdwr_ioctl_data ioctl_data = {msgs, 1};
	ret = ioctl(handle, I2C_RDWR, &ioctl_data);
	while(1){
		if (ret != 1 & count < 100) {
			ret = ioctl(handle, I2C_RDWR, &ioctl_data);
			count ++;
		}else if(ret != 1 & count >= 100){
			return false;
		}else{
			return true;
		}
	}
}
bool  read_i2c_device(int handle,int addr, unsigned char * pbuf)
{
	int ret;
	unsigned char buff[4] = {addr,0,0};

	ret=write(handle,buff,1);

	if(ret)
	{
		ret=read(handle,pbuf,4);
		if(ret)
		{
			//printf("%02X %02X %02X %02X \n",pbuf[0],pbuf[1],pbuf[2],pbuf[3]);
		}
	}

	return ret;
}
